import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;

public class RobClient implements Runnable, Client {

	//variables
	private Socket socket;
	private ArrayList<String> history = null;

	//writer
	private PrintWriter printWriter = null;

	//reader
	private BufferedReader bufferedReader = null;

	//constructor
	public RobClient() {
		history = new ArrayList<String>();
	}

	public void run() {
		// TODO Auto-generated method stub

	};

	public boolean connect(String ip, int port) {

		try {
			socket = new Socket(ip, port);

			//initialize writer
			printWriter = new PrintWriter(new OutputStreamWriter(
					socket.getOutputStream()));

			//initialize reader
			bufferedReader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));

		} catch (Exception e) {
			return false;
		}
		
		//build connection
		System.out.println("Verbindung aufbauen:");
		write("Hello Robot");
		System.out.println(read());
		if (read().equals("accepted")) {
			write("ResetAllowedStatus");
			read();
			return true;
		} else
			return false;

	}

	//send a message to the server
	void write(String message) {
		printWriter.print(message);
		printWriter.flush();
		history.add("W: " + message);
	}

	//read a message from the server
	public String read() {
		String message;
		String f = "failed";
		try {
			message = bufferedReader.readLine();
		} catch (IOException e) {
			e.printStackTrace();
			return f;
		}
		//System.out.println(message);
		history.add("R: " + message);
		return message;
	}
	
	public boolean writeAndRead(String message){
		write(message);
		String answer;
		while(true){
			answer = read();
			if(answer.equals("true")){
				return true;
			} else if(answer.equals("false")){
				return false;
			}
		}
	}

	//shows history
	public void showHistory() {
		for (int i = 0; i < history.size(); i++) {
			System.out.println(history.get(i));
		}

	}

}
